﻿using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using InterfaceLib;
using Ivony.Fluent;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ExtendLib.Helper
{
    /// <summary>
    /// 数据帮助
    /// </summary>
    public class DataHelper
    {
        /// <summary>
        /// 数据同步
        /// </summary>
        public static void DataSync()
        {
            var apiUrl = ConfigurationSettings.AppSettings["ApiUrl"];
            if(apiUrl.IsNullOrEmpty())
                return;
            var hri = new HttpRequestItem
            {
                Url = apiUrl,
                Method = "post",
                ContentType = "post",
                PostData ="v=1.1"
            };
            var json = HttpHelper.GetHtml(hri).DataInfo;
            if(json.IsNullOrEmpty())
                return;
            var dataList =JsonConvert.DeserializeObject<List<MsgModel>>(json);
            if(dataList.Count<=0)
                return;
            foreach (MsgModel item in dataList)
            {
                try
                {
                    var nowList = DbHelperByDapper.GetList<MsgModel>(new { item.BaseUrl, item.PostUrl, item.PostData }).ToList();
                    if (nowList.Any()) //根据这三个参数能确定唯一一条 修改参数
                    {
                        var nowItem = nowList[0];
                        //基本都相同 不用操作
                        if (nowItem.SuccessFlag == item.SuccessFlag && nowItem.Wait == item.Wait)
                        {
                            continue;
                        }
                        //更新
                        nowItem.SuccessFlag = item.SuccessFlag;
                        nowItem.Wait = item.Wait;
                        DbHelperByDapper.ModifyDb(nowItem);
                    }
                    else//有新增接口
                    {
                        DbHelperByDapper.InsertDb(item);
                    }
                }
                catch (System.Exception ex)
                {
                    LogHelper.WirteLog("同步异常。"+ex.Message);
                }
            }
            LogHelper.WirteLog("同步完成，同步数量：" + dataList.Count);
        }

    }
}
